IRCBot::Plugin.define 'calc' do
	help_string "Does calculations. It won't use floating-point numbers unless you tell it to. Supported operations are: +, -, *, /, ^, and sqrt() (addition, subtraction, multiplication, division, exponentiation, square root). Available constants are PI and E. Call using either \"calc <expression>\" or \"Marco, calculate <expression>\""
	@ans = ""
	def command(user,target,message,hostmask)
		privmsg(target,calculate(message))
	end
	
	def privmsg_function(user,target,message,hostmask)
		if message.downcase.start_with?("#{$config[$network]['nickname'].downcase}, calculate ") then
			message = message.downcase.sub("#{$config[$network]['nickname'].downcase}, calculate ",'').strip
			privmsg(target,calculate(message))
		end
	end
	
	def calculate(expr)
		# Stripping spaces
		expr = expr.gsub(" ","").upcase
		# Turning square roots into something more easily identified
		# Parensed square roots
		roots = expr.match(/sqrt\([0-9.^+-\/A-Z]+\)/)
		if roots != nil then
			roots = roots.to_a
			for root in roots
				expr.sub!(root,root.gsub(/(\(|\))/,""))
			end
		end
		expr.gsub!("ANS",@ans)
		expr.gsub!("SQRT","&")
		# Constants
		expr.gsub!("PI",Math::PI.to_s)
		expr.gsub!("E",Math::E.to_s)
		# Stripping out other stuff
		expr.gsub!(/[a-z]+|[A-Z]+/,"")
		# Turning ^ into ** (exponents)
		expr.gsub!("^","**")
		# Square roots and stuff
		roots = expr.match(/&[0-9.^+-\/A-Z]+/)
		if roots != nil then
			roots = roots.to_a
			roots.each do |root|
				expr.sub!(root,"Math.sqrt(#{root.sub("&","")})")
			end
		end
		begin
			@ans = eval(expr).to_s
			return @ans
		rescue Exception
			return "INVALID ARGUMENTS, CORRECT SOURCE AND RESUBNIT"
		end
	end
end
